﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Q.Extensions
{
    public static class TextReaderExtensions
    {
        public static UInt32? ReadUInt32(this TextReader reader)
        {
            UInt32 value = 0;
            int ch = -1;
            UInt32 i = 0;
            int readCount = 0;

            while (true)
            {
                ch = reader.Peek();

                if (ch != -1)
                {
                    char c = (char)ch;

                    if (Char.IsDigit(c))
                    {
                        i = UInt32.Parse(Convert.ToString(c));

                        checked
                        {
                            value *= 10;
                            value += i; 
                        }

                        reader.Read();
                        readCount++;
                    }
                    else if (readCount > 0)
                    {
                        return value;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    break;
                }
            }

            if (readCount > 0)
            {
                return value;
            }
            else
            {
                return null;
            }
        }

        public static UInt64? ReadUInt64(this TextReader reader)
        {
            UInt64 value = 0;
            int ch = -1;
            UInt64 i = 0;
            int readCount = 0;

            while (true)
            {
                ch = reader.Peek();

                if (ch != -1)
                {
                    char c = (char)ch;

                    if (Char.IsDigit(c))
                    {
                        i = UInt64.Parse(Convert.ToString(c));

                        checked
                        {
                            value *= 10;
                            value += i;
                        }

                        reader.Read();
                        readCount++;
                    }
                    else if (readCount > 0)
                    {
                        return value;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    break;
                }
            }

            if (readCount > 0)
            {
                return value;
            }
            else
            {
                return null;
            }
        }
    }
}
